package com.atguigu.yygh.msm.controller;

import com.atguigu.yygh.common.R;
import com.atguigu.yygh.msm.service.MsmService;
import com.atguigu.yygh.msm.utils.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Api(description = "短信管理")
@RestController
@RequestMapping("/api/msm")
public class MsmController {

    @Autowired
    private MsmService msmService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;


    @ApiOperation(value = "发送短信")
    @GetMapping(value = "/send/{phone}")
    public R code(@PathVariable String phone) {

        //先验证此手机号是否发送过短信
        String redisCode = redisTemplate.opsForValue().get(phone);
         if(!StringUtils.isEmpty(redisCode))return R.ok();
         //获取验证码
        String code = RandomUtil.getFourBitRandom();
        Map<String,Object> param=new HashMap<>();
        //跟短信模板参数对应
        param.put("code",code);
        boolean isSend=msmService.send(phone,param);
        //发送成功后 ，保存验证码， 设置5分钟内有效
        if(isSend){
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok();
        }else {
            return R.error();
        }





    }



    }
